package tech.aistar.ajax;

import com.alibaba.fastjson.JSONArray;
import tech.aistar.prj.entity.Result;
import tech.aistar.prj.entity.User;
import tech.aistar.prj.service.IUserService;
import tech.aistar.prj.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 本类功能:返回json数据
 *
 * @author cxylk
 * @date 2020/9/23 12:51
 */
@WebServlet(urlPatterns = "/ajax/check")
public class HelloGetAjaxAction extends HttpServlet {
    private IUserService userService=new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json;charset=utf-8");

        PrintWriter out=resp.getWriter();

        String username=req.getParameter("uname");

        //根据用户名查找用户
        User user=userService.login(username);

        Result result;

        if(null==user){
            //成功的...用户是不重复的
            result=new Result("200","用户名允许被使用");
        }else{
            result=new Result("500","用户名已存在");
        }

        //将java中的单个对象转换成json字符串
        String resultStr= JSONArray.toJSONString(result);

        //out.println(resultStr);//'{"id":i,"name":"tom"}\n'

        out.write(resultStr);
    }
}
